package com.atguigu.cloud.consumer.controller;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.cloud.stream.messaging.Sink;
import org.springframework.messaging.Message;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;


@RestController
@EnableBinding(Sink.class)
public class ReceiveMassageController {
    @Value("${server.port}")
    private String serverPort;


    @StreamListener(Sink.INPUT)
    public void input(Message<String> message,
                      @Header(AmqpHeaders.CHANNEL) Channel channel,
                      @Header(AmqpHeaders.DELIVERY_TAG) Long deliveryTag
    ) {
        final String messagePayload = message.getPayload();
        System.out.println("消费者2号,----->接受到的消息: " +
                messagePayload +
                "\t  port: " + serverPort);
        try {
            Thread.sleep(2000);
            System.out.println(serverPort + "消息处理完毕");
            channel.basicAck(deliveryTag, false);
            //之前未确认的消息都处理失败且将这些消息重新放回队列中
            //  第3个参数为false时,消息会被丢弃
            //channel.basicNack(deliveryTag, false,true);
        } catch (InterruptedException | IOException e) {
            e.printStackTrace();
        }
    }
}
